﻿using System;
using System.Collections.Generic;

namespace cludg.Web.Core.ViewRegister
{
	public class ViewRegisterContainer : IViewRegisterContainer
	{
		protected readonly Dictionary<Type, string> Views
			= new Dictionary<Type, string>();

		public void RegisterView(Type modelType, string viewName)
		{
			if (Views.ContainsKey(modelType))
			{
				Views[modelType] = viewName;
			}
			else
			{
				Views.Add(modelType, viewName);
			}
		}

		private string DoGetView(Type modelType)
		{
			if (!Views.ContainsKey(modelType))
			{
				Type parent = modelType.BaseType;
				return parent == null ? null : DoGetView(parent);
			}

			return Views[modelType];			
		}

		public string GetView(Type modelType)
		{
			var view = DoGetView(modelType);

			if (String.IsNullOrEmpty(view))
			{
				throw new ApplicationException(string.Format("For '{0}' model view is not registered!",
					modelType.FullName));
			}

			return view;
		}
	}
}
